package com.woniu.listener;

import com.rabbitmq.client.Channel;
import com.woniu.outlet.dao.ReliablePoMapper;
import com.woniu.outlet.po.ReliablePo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 采购消息监听
 */
@Component
public class PurchasePoMessageListener {

    @Autowired
    private ReliablePoMapper reliablePoMapper;
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}")
    private String sendPreson;

    @RabbitListener(queues = "purchase_queue")
    public void getMessage(Message message,Channel channel){
        //消息去重
        String messageId = message.getMessageProperties().getClusterId();
        ReliablePo reliablePo = new ReliablePo();
        reliablePo.setMessageid(Integer.parseInt(messageId));
        try {
            reliablePoMapper.insert(reliablePo);
        } catch (Exception e) {
            e.printStackTrace();
            //拒绝应答
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        //发送消息至审核人员
        String[] split = new String(message.getBody()).split("-");
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("采购单信息");
        mailMessage.setText("你有一天来自"+split[0]+"的采购单信息,单号:"+split[1]+
                "  请审阅"+"http://localhost:10002/purchaseById/"+split[1]);
        mailMessage.setTo("2876105102@qq.com");    //收件人的邮箱
        mailMessage.setFrom(sendPreson);  //发件人的邮箱，和配置的username保持一致
        javaMailSender.send(mailMessage);
    }
}
